package com.lovo.sheyingback.controller;

import com.lovo.sheyingback.bean.form.FileForm;
import com.lovo.sheyingback.result.ResponseResult;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.Date;

@RestController
public class IndexController {
    public static final String UPLOAD_PATH = "d:/server/upload";
    @DeleteMapping("/deleteFile")
    @ResponseResult
    public Object deleteFile(@RequestParam("file") String fileName){
        File file = new File(UPLOAD_PATH + "/" + fileName);
        return file.delete();
    }
    @DeleteMapping("/deleteFiles")
    @ResponseResult
    public Object deleteFiles(@RequestBody FileForm fileForm){
        Arrays.stream(fileForm.getFiles()).forEach(item -> new File(UPLOAD_PATH + "/" + item).delete());
        return true;
    }
    @PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file){
        // 获取上传图片的文件名
        String fileName = file.getOriginalFilename();
        // 截取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成新的文件名（时间 + 随机数 + 后缀名）
        String newFileName = new Date().getTime() + "_" + String.valueOf(Math.random()).substring(2) + suffixName;
        File targetFile = new File(UPLOAD_PATH, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        // 保存
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return newFileName;

    }
}
